﻿using Dapper;
using JX.Core;
using JX.Core.Entity;
using JX.Infrastructure.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace JX.Application
{
	public partial class RolesServiceAppDapper : ServiceAppDapper<RolesEntity>, IRolesServiceAppDapper
	{
		private char[] split = new char[] { ',' };

		#region 仓储接口
		private readonly IAdminRepositoryDapper _AdminRepository;
		private readonly IAdminRolesRepositoryDapper _AdminRolesRepository;
		private readonly IRolesPermissionsRepositoryDapper _RolesPermissionsRepository;
		private readonly IRoleFieldPermissionsRepositoryDapper _RoleFieldPermissionsRepository;
		private readonly IRoleNodePermissionsRepositoryDapper _RoleNodePermissionsRepository;
		private readonly IRoleSpecialPermissionsRepositoryDapper _RoleSpecialPermissionsRepository;
		private readonly ILogRepositoryDapper _LogRepository;
		/// <summary>
		/// 构造器注入
		/// </summary>
		/// <param name="repository"></param>
		/// <param name="adminRepository"></param>
		/// <param name="adminRolesRepository"></param>
		/// <param name="rolesPermissionsRepository"></param>
		/// <param name="roleFieldPermissionsRepository"></param>
		/// <param name="roleNodePermissionsRepository"></param>
		/// <param name="roleSpecialPermissionsRepository"></param>
		/// <param name="logRepository"></param>
		public RolesServiceAppDapper(IRolesRepositoryDapper repository,
			IAdminRepositoryDapper adminRepository,
			IAdminRolesRepositoryDapper adminRolesRepository,
			IRolesPermissionsRepositoryDapper rolesPermissionsRepository,
			IRoleFieldPermissionsRepositoryDapper roleFieldPermissionsRepository,
			IRoleNodePermissionsRepositoryDapper roleNodePermissionsRepository,
			IRoleSpecialPermissionsRepositoryDapper roleSpecialPermissionsRepository,
			ILogRepositoryDapper logRepository) : base(repository)
		{
			m_repository = repository;
			_AdminRepository = adminRepository;
			_AdminRolesRepository = adminRolesRepository;
			_RolesPermissionsRepository = rolesPermissionsRepository;
			_RoleFieldPermissionsRepository = roleFieldPermissionsRepository;
			_RoleNodePermissionsRepository = roleNodePermissionsRepository;
			_RoleSpecialPermissionsRepository = roleSpecialPermissionsRepository;
			_LogRepository = logRepository;
		}
		#endregion

		#region 删除角色和相关权限
		/// <summary>
		/// 通过主键删除角色。
		/// 1、删除字段的权限设置。
		/// 2、删除节点的权限设置。
		/// 3、删除专题的权限设置。
		/// 4、删除角色的权限设置。
		/// </summary>
		/// <returns></returns>
		public bool DeleteFull(System.Int32 roleID)
		{
			if (roleID <= 0)
			{
				return false;
			}
			DeleteRoleRelation(roleID);
			return Delete(p => p.RoleID == roleID);
		}
		/// <summary>
		/// 通过主键删除角色。
		/// 1、删除字段的权限设置。
		/// 2、删除节点的权限设置。
		/// 3、删除专题的权限设置。
		/// 4、删除角色的权限设置。
		/// </summary>
		/// <returns></returns>
		public async Task<bool> DeleteFullAsync(System.Int32 roleID)
		{
			if (roleID <= 0)
			{
				return false;
			}
			DeleteRoleRelation(roleID);
			return await DeleteAsync(p => p.RoleID == roleID);
		}

		/// <summary>
		/// 移除指定角色的所有专题权限
		/// </summary>
		/// <param name="roleID">角色ID，小于等于-1表示所有角色</param>
		/// <param name="specialId">专题ID，小于等于0表示所有专题</param>
		/// <param name="operateCode">权限码</param>
		/// <returns></returns>
		public async Task<bool> DeleteSpecialPermissionFromRoles(int roleID = -1, int specialId = 0, OperateCode operateCode = OperateCode.None)
		{
			string strCode = "";
			if (operateCode != OperateCode.None)
			{
				strCode = ((int)operateCode).ToString();
			}
			string strSpecialID = "";
			if (specialId > 0)
			{
				strSpecialID = specialId.ToString();
			}
			return await _RoleSpecialPermissionsRepository.DeleteSpecialPermissionFromRolesAsync(roleID, strSpecialID, strCode);
		}

		/// <summary>
		/// 删除角色相关的所有权限
		/// </summary>
		/// <param name="roleId"></param>
		private void DeleteRoleRelation(int roleId)
		{
			_RolesPermissionsRepository.DeletePermissionFromRoles(roleId);
			_RoleFieldPermissionsRepository.DeleteFieldPermissionFromRoles(roleId);
			_RoleNodePermissionsRepository.DeleteNodePermissionFromRoles(roleId);
			_RoleSpecialPermissionsRepository.DeleteSpecialPermissionFromRoles(roleId);
			_AdminRolesRepository.RemoveAdminFromRolesByRoleId(roleId);
		}
		#endregion

		#region 角色成员管理
		/// <summary>
		/// 得到属于指定角色的管理员列表，管理员不包括扩展属性
		/// </summary>
		/// <param name="roleID"></param>
		/// <returns></returns>
		public async Task<IList<AdminEntity>> GetMemberListByRoleID(int roleID)
		{
			var entityList = await _AdminRepository.GetListBySQLAsync<AdminEntity>("select * from Admin where AdminID IN (SELECT AdminID FROM AdminRoles WHERE (RoleID = @RoleID))", new { RoleID= roleID });
			return entityList.AsList();
		}

		/// <summary>
		/// 得到不属于指定角色的管理员列表，管理员不包括扩展属性
		/// </summary>
		/// <param name="roleID"></param>
		/// <returns></returns>
		public async Task<IList<AdminEntity>> GetMemberListNotInRole(int roleID)
		{
			var entityList = await _AdminRepository.GetListBySQLAsync<AdminEntity>("select * from Admin where AdminID NOT IN (SELECT AdminID FROM AdminRoles WHERE (RoleID = @RoleID))", new { RoleID = roleID });
			return entityList.AsList();
		}

		/// <summary>
		/// 添加管理员到角色
		/// </summary>
		/// <param name="admins">管理员ID，多个ID用“,”分隔</param>
		/// <param name="roleId"></param>
		/// <returns></returns>
		public async Task<bool> AddMembersToRole(string admins, int roleId)
		{
			_AdminRolesRepository.RemoveAdminFromRolesByRoleId(roleId);
			if (!string.IsNullOrEmpty(admins))
			{
				foreach (string str in admins.Split(split, StringSplitOptions.RemoveEmptyEntries))
				{
					await _AdminRolesRepository.AddAsync(new AdminRolesEntity() { AdminID = DataConverter.CLng(str), RoleID = roleId });
				}
			}
			return true;
		}
		#endregion

		#region 角色－菜单权限管理
		/// <summary>
		/// 检查当前管理员对指定操作是否有操作权限（按操作码名称）
		/// </summary>
		/// <param name="operateCode"></param>
		/// <returns></returns>
		public bool AccessCheck(string operateCode)
		{
			if (string.IsNullOrEmpty(operateCode))
			{
				return false;
			}
			if (operateCode == "None")
			{
				return true;
			}
			if (MyHttpContext.IsSuperAdmin)
			{
				return true;
			}
			return IsInRole(GetRoleIdListByOperatorCode(operateCode));
		}
		/// <summary>
		/// 检查指定管理员对指定操作是否有操作权限
		/// </summary>
		/// <param name="operateCode">操作码</param>
		/// <param name="adminName">管理员名称</param>
		/// <returns></returns>
		public bool AccessCheck(string operateCode, string adminName)
		{
			var adminEntity = _AdminRepository.GetEntityFull(p => p.AdminName == adminName);
			if (adminEntity == null)
				return false;
			if (adminEntity.RoleIDs == "0")
				return true;
			IList<string> roleIdListByOperatorCode = GetRoleIdListByOperatorCode(operateCode);
			IList<string> roleIdListByAdminName = StringHelper.GetArrayBySplit<string>(adminEntity.RoleIDs);
			foreach (string str in roleIdListByOperatorCode)
			{
				foreach (string str2 in roleIdListByAdminName)
				{
					if (str == str2)
					{
						return true;
					}
				}
			}
			return false;
		}

		/// <summary>
		/// 添加权限到角色，并清除对应权限的缓存数据
		/// </summary>
		/// <param name="roleID"></param>
		/// <param name="operateCodes">多个权限码用“,”分隔</param>
		/// <returns></returns>
		public async Task<bool> AddPermissionToRoles(int roleID, string operateCodes)
		{
			if (roleID <= 0 || string.IsNullOrEmpty(operateCodes))
				return false;
			var arrOperateCodes = operateCodes.Split(split, StringSplitOptions.RemoveEmptyEntries);
			arrOperateCodes = StringHelper.RemoveRepeatItem(arrOperateCodes);
			foreach (string str in arrOperateCodes)
			{
				if (!string.IsNullOrEmpty(str) && (str != "None"))
				{
					await _RolesPermissionsRepository.AddAsync(new RolesPermissionsEntity() { RoleID = roleID, OperateCode = str });
				}
			}
			RemoveAllCache();
			return true;
		}

		/// <summary>
		/// 移除指定角色的所有常规权限
		/// </summary>
		/// <param name="roleID"></param>
		/// <returns></returns>
		public async Task<bool> DeletePermissionFromRoles(int roleID)
		{
			bool flag = await _RolesPermissionsRepository.DeletePermissionFromRolesAsync(roleID);
			if (flag)
			{
				RemoveAllCache();
			}
			return flag;
		}

		/// <summary>
		/// 得到指定角色的所有权限码
		/// </summary>
		/// <param name="roleID"></param>
		/// <returns></returns>
		public async Task<IList<RolesPermissionsEntity>> GetRolesPermissionsByRoleID(int roleID)
		{
			var entityList = await _RolesPermissionsRepository.GetListAsync(p => p.RoleID == roleID);
			return entityList.AsList();
		}

		/// <summary>
		/// 得到指定权限码的所有角色
		/// </summary>
		/// <param name="operateCode"></param>
		/// <returns></returns>
		public async Task<IList<RolesPermissionsEntity>> GetRolesPermissionsByOperateCode(string operateCode)
		{
			var entityList = await _RolesPermissionsRepository.GetListAsync(p => p.OperateCode == operateCode);
			return entityList.AsList();
		}
		/// <summary>
		/// 按操作权限码获取角色列表
		/// </summary>
		/// <param name="operateCode"></param>
		/// <returns></returns>
		public IList<string> GetRoleIdListByOperatorCode(string operateCode)
		{
			IList<string> roleListByOperateCode = CacheHelper.CacheServiceProvider.Get("CK_OperatorCode_" + operateCode) as IList<string>;
			if (roleListByOperateCode == null)
			{
				var roleList = _RolesPermissionsRepository.GetAllData<RolesPermissionsEntity, int?>(selector: p => p.RoleID, predicate: p => p.OperateCode == operateCode).ToList();
				roleListByOperateCode = roleList.ConvertAll(x => x.ToString());
				if (roleListByOperateCode.Count > 0)
				{
					CacheHelper.CacheServiceProvider.AddOrUpdate("CK_OperatorCode_" + operateCode, roleListByOperateCode,TimeSpan.FromDays(1),true);
				}
			}
			return roleListByOperateCode;
		}
		#endregion

		#region 角色－节点权限管理
		/// <summary>
		/// 检查对指定节点的父节点是否有操作权限,(判断指定节点或其父节点是否在指定节点集中)
		/// </summary>
		/// <param name="operateCode"></param>
		/// <param name="nodeInfo"></param>
		/// <param name="arrNodeIds"></param>
		/// <returns></returns>
		public bool AccessCheckNodeParentPermission(OperateCode operateCode, NodesEntity nodeInfo, string arrNodeIds)
		{
			string findStr = nodeInfo.NodeID.ToInt32().ToString();
			if (nodeInfo.ParentID > 0)
			{
				findStr = findStr + "," + nodeInfo.ParentPath;
			}
			return StringHelper.FoundCharInArr(arrNodeIds, findStr);
		}
		/// <summary>
		/// 检查当前管理员对指定节点是否有指定操作的权限
		/// </summary>
		/// <param name="operateCode"></param>
		/// <param name="nodeId"></param>
		/// <returns></returns>
		public bool AccessCheckNodePermission(OperateCode operateCode, int nodeId)
		{
			if (MyHttpContext.IsSuperAdmin)
				return true;
			string emnuValue = ((int)operateCode).ToString();
			var roleList = _RoleNodePermissionsRepository.GetAllData<RoleNodePermissionsEntity,int?>(selector:p=>p.RoleID,predicate:p => p.OperateCode == emnuValue && p.NodeID == nodeId).ToList();
			return IsInRole(roleList.ConvertAll(x => x.ToString()));
		}
		/// <summary>
		/// 判断指定节点集是否存在指定权限码的权限项
		/// </summary>
		/// <param name="nodeId">节点ID，多个ID用“,”分隔</param>
		/// <param name="operateCode"></param>
		/// <returns></returns>
		public bool AccessCheckNodePermissions(string nodeId, OperateCode operateCode)
		{
			if (!DataValidator.IsValidId(nodeId))
			{
				return false;
			}
			string emnuValue = ((int)operateCode).ToString();
			var arrIDs = StringHelper.GetArrayBySplit<int?>(nodeId).ToArray();
			return _RoleNodePermissionsRepository.IsExist(p => p.OperateCode == emnuValue && arrIDs.Contains(p.NodeID));
		}

		/// <summary>
		/// 添加节点权限到角色
		/// </summary>
		/// <param name="roleID"></param>
		/// <param name="nodeIdAndOperateCode">节点ID与权限码的集合体，多个内容用“,”分隔（例：-2:101005001,-2:101005002）</param>
		/// <returns></returns>
		public async Task<bool> AddNodePermissionToRoles(int roleID, string nodeIdAndOperateCode)
		{
			if (roleID <= 0 || string.IsNullOrEmpty(nodeIdAndOperateCode))
				return false;

			var arrNodeIdAndOperateCode = nodeIdAndOperateCode.Split(split, StringSplitOptions.RemoveEmptyEntries);
			arrNodeIdAndOperateCode = StringHelper.RemoveRepeatItem(arrNodeIdAndOperateCode);
			foreach (string strItem in arrNodeIdAndOperateCode)
			{
				if (!string.IsNullOrEmpty(strItem))
				{
					var arrItem = strItem.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
					var nodeID = DataConverter.CLng(arrItem[0]);
					var operateCodes = arrItem[1];

					await _RoleNodePermissionsRepository.AddAsync(new RoleNodePermissionsEntity() { RoleID = roleID, OperateCode = operateCodes, NodeID = nodeID });
				}
			}
			RemoveAllCache();
			return true;
		}
		/// <summary>
		/// 添加节点权限到角色
		/// </summary>
		/// <param name="roleId"></param>
		/// <param name="nodeId"></param>
		/// <param name="operateCode"></param>
		public void AddNodePermissionToRoles(int roleId, int nodeId, OperateCode operateCode)
		{
			string emnuValue = ((int)operateCode).ToString();
			_RoleNodePermissionsRepository.Add(new RoleNodePermissionsEntity() { RoleID = roleId, OperateCode = emnuValue, NodeID = nodeId });
			RemoveAllCache();
		}
		/// <summary>
		/// 添加节点权限到角色列表
		/// </summary>
		/// <param name="roles">,分隔的ID列表</param>
		/// <param name="nodeId">节点ID</param>
		/// <param name="operateCode">操作码</param>
		public void AddNodePermissionToRoles(string roles, int nodeId, OperateCode operateCode)
		{
			foreach (string str in roles.Split(split, StringSplitOptions.RemoveEmptyEntries))
			{
				AddNodePermissionToRoles(DataConverter.CLng(str), nodeId, operateCode);
			}
		}
		/// <summary>
		/// 添加节点集权限到角色
		/// </summary>
		/// <param name="roleId"></param>
		/// <param name="operateCode"></param>
		/// <param name="nodeIds">节点ID，多个ID用“,”分隔</param>
		public void AddNodePermissionToRoles(int roleId, OperateCode operateCode, string nodeIds)
		{
			foreach (string str in nodeIds.Split(split, StringSplitOptions.RemoveEmptyEntries))
			{
				AddNodePermissionToRoles(roleId, DataConverter.CLng(str), operateCode);
			}
		}

		/// <summary>
		/// 移除指定角色的所有节点权限
		/// </summary>
		/// <param name="roleID">角色ID，小于等于-1表示所有角色</param>
		/// <param name="nodeId">节点ID，小于等于-3表示所有节点</param>
		/// <param name="operateCode">权限码</param>
		/// <returns></returns>
		public async Task<bool> DeleteNodePermissionFromRoles(int roleID = -1, int nodeId = -3, OperateCode operateCode = OperateCode.None)
		{
			string strCode = "";
			if (operateCode != OperateCode.None)
			{
				strCode = ((int)operateCode).ToString();
			}
			string strNodeID = "";
			if (nodeId > -3)
			{
				strNodeID = nodeId.ToString();
			}
			var flag = await _RoleNodePermissionsRepository.DeleteNodePermissionFromRolesAsync(roleID, strNodeID, strCode);
			if(flag)
			{
				RemoveAllCache();
			}
			return flag;
		}

		/// <summary>
		/// 获取指定管理员名称的所有节点的权限列表
		/// </summary>
		/// <param name="adminName"></param>
		/// <returns></returns>
		public IList<RoleNodePermissionsEntity> GetAllNodePermissionsByAdminName(string adminName)
		{
			IList<RoleNodePermissionsEntity> list = new List<RoleNodePermissionsEntity>();
			if (!string.IsNullOrEmpty(adminName))
			{
				list = _RoleNodePermissionsRepository.GetList(" AND RoleID IN (SELECT RoleID FROM AdminRoles WHERE AdminID = (SELECT AdminID FROM Admin WHERE AdminName = @AdminName)) ORDER BY NodeID ASC", new { AdminName = adminName }).ToList();
			}
			return list;
		}
		/// <summary>
		/// 获取指定管理员的所有节点的权限列表
		/// </summary>
		/// <param name="adminID"></param>
		/// <returns></returns>
		public IList<RoleNodePermissionsEntity> GetAllNodePermissionsByAdminID(int adminID)
		{
			IList<RoleNodePermissionsEntity> list = new List<RoleNodePermissionsEntity>();
			if (adminID > 0)
			{
				list = _RoleNodePermissionsRepository.GetList(" AND RoleID IN (SELECT RoleID FROM AdminRoles WHERE AdminID = @AdminID) ORDER BY NodeID ASC", new { AdminID = adminID }).ToList();
			}
			return list;
		}
		/// <summary>
		/// 获取指定角色、指定节点的权限列表
		/// </summary>
		/// <param name="roleId">角色ID，小于等于-1表示所有角色</param>
		/// <param name="nodeId">节点ID，小于等于-3表示所有节点，-2表示首页节点</param>
		/// <returns></returns>
		public IList<RoleNodePermissionsEntity> GetNodePermissionsById(int roleId = -1, int nodeId = -3)
		{
			Expression<Func<RoleNodePermissionsEntity, bool>> predicate = p => true;
			if (roleId >= 0)
			{
				predicate = predicate.And(p => p.RoleID == roleId);
			}
			if (nodeId >= -2)
			{
				predicate = predicate.And(p => p.NodeID == nodeId);
			}
			var entityList = _RoleNodePermissionsRepository.GetList(predicate);
			return entityList.AsList();
		}
		/// <summary>
		/// 获取指定角色、指定节点的权限列表
		/// </summary>
		/// <param name="roleId">角色ID，小于等于-1表示所有角色</param>
		/// <param name="nodeId">节点ID，小于等于-3表示所有节点，-2表示首页节点</param>
		/// <returns></returns>
		public async Task<IList<RoleNodePermissionsEntity>> GetNodePermissionsByIdAsync(int roleId = -1, int nodeId = -3)
		{
			Expression<Func<RoleNodePermissionsEntity, bool>> predicate = p => true;
			if (roleId >= 0)
			{
				predicate = predicate.And(p => p.RoleID == roleId);
			}
			if (nodeId >= -2)
			{
				predicate = predicate.And(p => p.NodeID == nodeId);
			}
			var entityList = await _RoleNodePermissionsRepository.GetListAsync(predicate);
			return entityList.AsList();
		}

		/// <summary>
		/// 获取指定角色ID集有指定权限的节点ID集
		/// </summary>
		/// <param name="roleId">角色ID，多个ID用“,”分隔</param>
		/// <param name="operateCode"></param>
		/// <returns></returns>
		public string GetRoleNodeId(string roleId, OperateCode operateCode=OperateCode.None)
		{
			if (!DataValidator.IsValidId(roleId))
			{
				return string.Empty;
			}
			string strWhere = " and RoleID IN @ids ";
			if(operateCode != OperateCode.None)
			{
				strWhere += " AND OperateCode = @OperateCode";
			}
			var nodeIdList = _RoleNodePermissionsRepository.GetAllData<string>(tableName: "", strExtended: "DISTINCT NodeID", strWhere: strWhere, param: new { ids = StringHelper.GetArrayBySplit<int>(roleId).ToArray(), OperateCode = (int)operateCode }).ToArray();
			return StringHelper.GetArrayString(nodeIdList,",");
		}
		/// <summary>
		/// 获取指定角色ID集有指定权限集的节点ID集
		/// </summary>
		/// <param name="roleId">角色ID，多个ID用“,”分隔</param>
		/// <param name="arrOperateCode"></param>
		/// <returns></returns>
		public string GetRoleNodeId(string roleId, OperateCode[] arrOperateCode)
		{
			if (!DataValidator.IsValidId(roleId))
			{
				return string.Empty;
			}
			string strWhere = " and RoleID IN @ids ";
			foreach (OperateCode code in arrOperateCode)
			{
				strWhere += " OR OperateCode = " + ((int)code);
			}
			var nodeIdList = _RoleNodePermissionsRepository.GetAllData<string>(tableName: "", strExtended: "DISTINCT NodeID", strWhere: strWhere, param: new { ids = StringHelper.GetArrayBySplit<int>(roleId).ToArray() }).ToArray();
			return StringHelper.GetArrayString(nodeIdList, ",");
		}
		#endregion

		#region 角色－模型字段权限管理
		/// <summary>
		/// 检查当前管理员是否对指定模型指定字段有操作权限
		/// </summary>
		/// <param name="operateCode"></param>
		/// <param name="modelId"></param>
		/// <param name="fieldName"></param>
		/// <returns></returns>
		public async Task<bool> AccessCheckFieldPermission(OperateCode operateCode, int modelId, string fieldName)
		{
			if (MyHttpContext.IsSuperAdmin)
				return true;
			var enumValue = ((int)operateCode).ToString();
			var roleList = await _RoleFieldPermissionsRepository.GetAllDataAsync<RoleFieldPermissionsEntity, int?>(predicate: p => p.OperateCode == enumValue && p.ModelID == modelId && p.FieldName == fieldName, selector: p => p.RoleID);
			bool result = IsInRole(roleList.ToList().ConvertAll(x => x.ToString()));
			return result;
		}

		/// <summary>
		/// 添加字段权限到角色集
		/// </summary>
		/// <param name="roleIDs">角色集</param>
		/// <param name="modelId">模型ID</param>
		/// <param name="fieldName">字段名</param>
		/// <param name="operateCode">权限码</param>
		/// <returns></returns>
		public async Task<bool> AddFieldPermissionToRoles(string roleIDs, int modelId, string fieldName, OperateCode operateCode)
		{
			if ((modelId <= 0) || string.IsNullOrEmpty(fieldName))
			{
				return false;
			}
			await DeleteFieldPermissionFromRoles(-1, modelId, fieldName);
			foreach (string str in roleIDs.Split(split, StringSplitOptions.RemoveEmptyEntries))
			{
				await _RoleFieldPermissionsRepository.AddAsync(new RoleFieldPermissionsEntity() { RoleID = str.ToInt32(), OperateCode = ((int)operateCode).ToString(), ModelID = modelId, FieldName = fieldName });
			}
			RemoveAllCache();
			return true;
		}
		/// <summary>
		/// 添加模型字段权限到角色
		/// </summary>
		/// <param name="roleID"></param>
		/// <param name="operateCodes">权限码</param>
		/// <param name="modelIdAndFieldName">模型ID与字段名的集合体，多个内容用“,”分隔（例：11:FieldName,11:FieldName1）</param>
		/// <returns></returns>
		public async Task<bool> AddFieldPermissionToRoles(int roleID, OperateCode operateCodes, string modelIdAndFieldName)
		{
			if (roleID <= 0 || string.IsNullOrEmpty(modelIdAndFieldName))
				return false;

			var arrModelIdAndFieldName = modelIdAndFieldName.Split(split, StringSplitOptions.RemoveEmptyEntries);
			arrModelIdAndFieldName = StringHelper.RemoveRepeatItem(arrModelIdAndFieldName);
			foreach (string strItem in arrModelIdAndFieldName)
			{
				if (!string.IsNullOrEmpty(strItem))
				{
					var arrItem = strItem.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
					var modelID = DataConverter.CLng(arrItem[0]);
					var fieldName = arrItem[1];

					await _RoleFieldPermissionsRepository.AddAsync(new RoleFieldPermissionsEntity() { RoleID = roleID, OperateCode = ((int)operateCodes).ToString(), ModelID = modelID, FieldName = fieldName });
				}
			}
			RemoveAllCache();
			return true;
		}
		/// <summary>
		/// 移除指定角色的所有模型字段权限
		/// </summary>
		/// <param name="roleID">角色ID，小于等于0表示所有角色</param>
		/// <param name="modelID">模型ID，小于等于0表示所有模型</param>
		/// <param name="fieldName">字段名，空或NULL表示所有字段</param>
		/// <returns></returns>
		public async Task<bool> DeleteFieldPermissionFromRoles(int roleID = 0, int modelID = 0, string fieldName = "")
		{
			RemoveAllCache();
			return await _RoleFieldPermissionsRepository.DeleteFieldPermissionFromRolesAsync(roleID, modelID, fieldName);
		}
		/// <summary>
		/// 获取指定角色、指定模型的字段权限列表
		/// </summary>
		/// <param name="roleId">角色ID，小于等于-1表示所有角色</param>
		/// <param name="modelId">模型ID，小于等于0表示所有模型</param>
		/// <param name="fieldName">字段名</param>
		/// <param name="operateCode">权限码</param>
		/// <returns></returns>
		public async Task<IList<RoleFieldPermissionsEntity>> GetFieldPermissionsById(int roleId = -1, int modelId = 0, string fieldName = "", OperateCode operateCode= OperateCode.None)
		{
			Expression<Func<RoleFieldPermissionsEntity, bool>> predicate = p => true;
			if (roleId >= 0)
			{
				predicate = predicate.And(p => p.RoleID == roleId);
			}
			if (modelId > 0)
			{
				predicate = predicate.And(p => p.ModelID == modelId);
			}
			if (!string.IsNullOrEmpty(fieldName))
			{
				predicate = predicate.And(p => p.FieldName == fieldName);
			}
			if (operateCode != OperateCode.None)
			{
				predicate = predicate.And(p => p.OperateCode == ((int)operateCode).ToString());
			}
			var entityList = await _RoleFieldPermissionsRepository.GetListAsync(predicate);
			return entityList.AsList();
		}

		#endregion

		#region 审核流程权限管理
		/// <summary>
		/// 获取审核流程的下一审核角色集
		/// </summary>
		/// <param name="flowId"></param>
		/// <returns></returns>
		public IList<RolesEntity> GetRoleListByFlowId(int flowId)
		{
			return m_repository.GetList(" (NOT EXISTS(SELECT NULL FROM RolesProcess AS P WHERE FlowId = @FlowId AND Roles.RoleID = P.RoleID))", new { FlowId = flowId }).ToList();
		}
		/// <summary>
		/// 获取不在指定流程处理进程中的角色列表
		/// </summary>
		/// <param name="flowId"></param>
		/// <param name="processId"></param>
		/// <returns></returns>
		public IList<RolesEntity> GetRoleListByFlowIdAndProcessId(int flowId, int processId)
		{
			return m_repository.GetList(" (NOT EXISTS(SELECT NULL AS Exp FROM RolesProcess AS P WHERE P.FlowId = @FlowId AND P.ProcessId != @ProcessId AND Roles.RoleID = P.RoleID))", new { FlowId = flowId, ProcessId= processId }).ToList();
		}
		#endregion

		/// <summary>
		/// 检查当前管理员是否属于指定的角色列表
		/// </summary>
		/// <param name="roleIdList"></param>
		/// <returns></returns>
		private bool IsInRole(IEnumerable<string> roleIdList)
		{
			foreach (var item in roleIdList)
			{
				if (MyHttpContext.IsInRoleID(item))
				{
					return true;
				}
			}
			return false;
		}
		/// <summary>
		/// 删除所有缓存
		/// </summary>
		private void RemoveAllCache()
		{
			CacheHelper.CacheServiceProvider.RemoveCacheRegex(@"CK_OperatorCode_\S*");
		}
	}
}
